package com.s666.demo.utils;

import javax.crypto.spec.SecretKeySpec;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


public class Aes {

	public static String encrypt(String input, String key){

	byte[] crypted = null;

	try{

	SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");

	Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

	cipher.init(Cipher.ENCRYPT_MODE, skey);

	crypted = cipher.doFinal(input.getBytes());

	}catch(Exception e){

		System.out.println(e.toString());

	}

	return Base64.encode(crypted);

}

 

public static String  decrypt(String input, String key){

	byte[] output = null;

	try{

	SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");

	Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

	cipher.init(Cipher.DECRYPT_MODE, skey);

	output = cipher.doFinal(Base64.decode(input));

	}catch(Exception e){

	System.out.println(e.toString());

	}

	return new String(output);

}

 

public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException, UnsupportedEncodingException {

		String key = "A91DBAB64154FE7A";

		String data = "This is java bcprovlib 中国pkcs7padding PKCS7 TEST222";
	
		String enStr =  Aes.encrypt(data, key);
		
		System.out.println(enStr);

		System.out.println( new String(Aes.decrypt(enStr, key))  );

	}	

}